package com.code.test.dance;

import com.code.test.first.tree.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 *
 * https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/description/
 * 103. 二叉树的锯齿形层序遍历
 * 给你二叉树的根节点 root ，返回其节点值的 锯齿形层序遍历 。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）。
 */
public class TreePrintZ {

    public static void main(String[] args) {
        TreeNode left10 = new TreeNode(10, null, null);
        TreeNode right20 = new TreeNode(5, null, null);
        TreeNode left30 = new TreeNode(30, null, null);
        TreeNode right40 = new TreeNode(4, null, null);
        TreeNode left3 = new TreeNode(2, null, right20);
        TreeNode right5 = new TreeNode(3, null, right40);
        TreeNode root = new TreeNode(1, left3, right5);

        List<List<Integer>> ret = zigzagLevelOrder(root);
        System.out.println(ret);
    }

    public  static List<List<Integer>> zigzagLevelOrder(TreeNode root) {

        Queue<TreeNode> que = new LinkedList();
        que.add(root);

        List<List<Integer>> ret = new ArrayList();

        boolean fromLeft2Right = true;
        while (!que.isEmpty()) {
            Deque<Integer> level = new LinkedList();

            int size = que.size();

            for (int i = 0; i < size; i++) {
                TreeNode node = que.poll();
                if (node != null) {
                    if (fromLeft2Right) {
                        level.offerLast(node.val);
                    } else {
                        level.offerFirst(node.val);
                    }

                    if (node.left != null) {
                        que.add(node.left);
                    }
                    if (node.right != null) {
                        que.add(node.right);
                    }
                }
            }
            if (level.size() > 0) {
                ret.add(new LinkedList<Integer>(level));
            }

            fromLeft2Right = !fromLeft2Right;
        }
        return ret;
    }
}
